<?php

namespace app\common\model;

use app\common\controller\Queue;
use app\common\library\Weixin;
use app\common\service\OrderService;
use think\Db;
use think\Exception;
use think\Model;


class OrderGroup extends Model
{

    

    

    // 表名
    protected $name = 'order_group';
    
    // 自动写入时间戳字段
    protected $autoWriteTimestamp = 'int';

    // 定义时间戳字段名
    protected $createTime = 'create_time';
    protected $updateTime = 'update_time';
    protected $deleteTime = false;

    // 追加属性
    protected $append = [
        'success_time_text',
	    'status_text'
    ];
    
	const STATUS_PAY = 0;
	const STATUS_ING = 1;
	const STATUS_SUCCESS = 2;
	const STATUS_FAIL = 3;
 
	public static $statusList = [
		self::STATUS_ING => '拼团中',
		self::STATUS_PAY => '待付款',
		self::STATUS_SUCCESS => '拼团成功',
		self::STATUS_FAIL => '拼团失败'
	];

	public function getStatusTextAttr($value, $data) {
		$value = $value ? : $data['status'];
		$list = self::$statusList;
		return $list[$value] ??'';
	}


    public function getSuccessTimeTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['success_time']) ? $data['success_time'] : '');
        return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
    }

    protected function setSuccessTimeAttr($value)
    {
        return $value === '' ? null : ($value && !is_numeric($value) ? strtotime($value) : $value);
    }
	
	public function user() {
		return $this->belongsTo('user', 'user_id', 'id', '', 'left')->setEagerlyType(0);
	}
	/**
	 * 更改拼团数量
	 * @param $id
	 * @param $goods
	 * @return bool
	 * @throws \think\Exception
	 * @throws \think\db\exception\DataNotFoundException
	 * @throws \think\db\exception\ModelNotFoundException
	 * @throws \think\exception\DbException
	 * @throws \think\exception\PDOException
	 */
    public function changeNumber($id, $goods) {
	    $goodsInfo = json_decode($goods['goods_info'], true);
		$group = $this->find($id);
		$data['number'] = $group['number'] + 1;
		
		//待支付成功的团
		if($group['status'] == self::STATUS_PAY) {
			$data['start_time'] = time();
			$data['end_time'] = time()+$goodsInfo['group_hour']*3600;
			$data['status'] = self::STATUS_ING;
		}
		
		//拼团成功
		if($data['number'] >= $goodsInfo['group_number']) {
			$data['status'] = self::STATUS_SUCCESS;
			$data['success_time'] = time();
			
			//更改自取拼团订单为待核销
			$orderRes = Db::name('order')
				->where(['group_id' => $id, 'status' => Order::STATUS_GROUP, 'sign_type' => Order::SIGN_TYPE_SELF])
				->update(['status' => Order::STATUS_SIGN, 'rebate_status' => Order::REBATE_CAL]);
			
			//更改快递订单为待发货
			$orderShippingRes = Db::name('order')
				->where(['group_id' => $id, 'status' => Order::STATUS_GROUP, 'sign_type' => Order::SIGN_TYPE_SHIPPING])
				->update(['status' => Order::STATUS_WAIT_SHIPPING, 'rebate_status' => Order::REBATE_CAL]);
			
			if($orderRes === false || $orderShippingRes === false) {
				$this->error = '更改拼团订单状态出错';
				return false;
			}
			
			$orders = Db::name('order')
				->where(['group_id' => $id, 'status' => Order::STATUS_SIGN])
				->column('area', 'id');
			
			
			if($orders) {
				foreach ($orders as $orderId => $area) {
					$serverObj = new OrderService();
					$successRes = $serverObj->rebate($orderId);
					if(!$successRes) {
						$this->error = $serverObj->getError();
						return false;
					}
				}
			}

			//发送模板消息
			Queue::addTask('sendTemplate', [
				'type' => 'groupSuccess',
				'groupId' => $id
			]);
		}
		
		$res = Db::name('orderGroup')->where(['id' => $id])->update($data);
		if(!$res) {
			$this->error = '更改拼团数量出错';
			return false;
		}
		
		return true;
    }
	
	/**
	 * 发送拼团模板消息
	 * @param $groupId
	 * @param $type
	 * @return bool
	 * @throws \think\Exception
	 * @throws \think\db\exception\DataNotFoundException
	 * @throws \think\db\exception\ModelNotFoundException
	 * @throws \think\exception\DbException
	 */
    public function sendGroupTemplate($groupId, $type) {
		$orders = Db::name('order')->alias('o')
			->join('user u', 'o.user_id = u.id', 'left')
			->join('orderGoods g', 'o.id = g.order_id', 'left')
			->where(['o.group_id' => $groupId])
			->field('u.smallapp_openid, o.order_no, o.id, o.user_id, o.code, g.goods_info')
			->select();
		$str = '';
		if($orders) {
			$config = config('weixin');
			$appid = $config['smallapp']['app_id'];
			$obj = new Weixin($appid);
			
			$ids = [];
			foreach ($orders as $order) {
				$form = Db::name('formId')->where(['number' => 0, 'user_id' => $order['user_id'], 'create_time' => ['egt', strtotime('-7 days')]])
					->order(['create_time' => 'asc'])
					->find();
				if(!$form) {
					$str .= $order['id'].'没有模板ID;';
					continue;
				}
				$goodsInfo = json_decode($order['goods_info'], true);
				if($type == 'success') {
					$templateId = $config['smallapp']['message_template']['group_success'];
					$data = [
						'keyword1' => ['value' => $goodsInfo['name']],
						'keyword2' => ['value' => $order['code']],
						'keyword3' => ['value' => $order['order_no']],
						'keyword4' => ['value' => '拼团得红包，拼团成功，快来领取红包吧！'],
					];
					$page = 'pages/order/hb?id='.$order['id'];
				} else {
					$templateId = $config['smallapp']['message_template']['group_fail'];
					$data = [
						'keyword1' => ['value' => $goodsInfo['name']],
						'keyword2' => ['value' => '人数未满'],
						'keyword3' => ['value' => $order['order_no']],
					];
					$page = 'pages/goods/detail?id='.$goodsInfo['id'].'&group_id='.$groupId;
				}
				$res = $obj->sendTemplate($order['smallapp_openid'], $templateId, $form['form_id'],$data, $page);
				if($res === true) {
					$ids[]	 = $form['id'];
				}
				$str .= $order['id'].'结果:'.$res.';';
				
			}
			
			if($ids) {
				Db::name('formId')->where(['id' => ['in', $ids]])->setInc('number');
			}
			
		}
		
		return $str;
    }
	
	/**
	 * @param $id 团ID
	 * @return bool
	 * @throws \think\exception\PDOException
	 */
    public function fail($id) {
    	$this->startTrans();
        try {
        	//更改拼团状态
	        $groupRes = $this->save(['status' => self::STATUS_FAIL], ['id' => $id]);
	        if(!$groupRes) {
	        	throw new Exception('更改团状态出错');
	        }
	        
	        
	        //关闭订单
	        $orderModel = new Order();
	        $orderRes = $orderModel->save([
	            'status' => $orderModel::STATUS_CLOSE,
		        'close_reason' => $orderModel::CANCEL_REASON_GROUP_FAIL,
		        
	        ],['group_id' => $id]);
	        
	        if(!$orderRes) {
	        	throw new Exception('更改订单状态出错');
	        }
	        
	        //支付成功的订单退款
	        $orders = Db::name('order')
		        ->where(['group_id' => $id, 'pay_status' => $orderModel::PAY_STATUS_Y])
		        ->field('id, amount, transaction_no')
		        ->select();
	        if($orders) {
		        $config = config('weixin');
		        $weixin = new Weixin($config['smallapp']['app_id']);
		        foreach ($orders as $order) {
			        $refundNo = time().mt_rand(100000, 999999);
			        $res = $weixin->refund($order['transaction_no'], $refundNo, $order['amount'],$order['amount'], '拼团失败退款');
					if($res) {
						$payStatus = Order::PAY_STATUS_REFUND;
					} else {
						$payStatus = Order::PAY_STATUS_REFUND_FAIL;
					}
			        $payRes = Db::name('order')->where('id', $order['id'])->update(['pay_status' => $payStatus]);
					if(!$payRes) {
						throw new Exception('更改支付状态出错');
					}
		        }
	        }
	       
		       
	        //发送模板消息
	        Queue::addTask('sendTemplate', [
		        'type' => 'groupFail',
		        'groupId' => $id
	        ]);
		       
        	
        	$this->commit();
        	return true;
        } catch (Exception $e) {
        	$this->rollback();
        	$this->error = $e->getMessage();
        	return false;
        }
    }
}

